package com.socialsoftware.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.socialsoftware.R;
import com.socialsoftware.model.Contact;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 搜索结果适配器
 * 用于显示搜索到的好友列表
 */
public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder> {
    
    private Context context;
    private List<Contact> results;
    private OnResultClickListener listener;
    
    // 记录已添加好友的状态
    private Map<String, Integer> addFriendStatus = new HashMap<>();
    
    // 添加好友状态常量
    public static final int STATUS_NOT_ADDED = 0;       // 未添加
    public static final int STATUS_REQUESTING = 1;      // 请求中
    public static final int STATUS_REQUEST_SENT = 2;    // 已发送请求
    public static final int STATUS_ADDED = 3;           // 已添加
    
    public SearchResultAdapter(Context context, List<Contact> results) {
        this.context = context;
        this.results = results;
    }
    
    public void setOnResultClickListener(OnResultClickListener listener) {
        this.listener = listener;
    }
    
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_search_result, parent, false);
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Contact contact = results.get(position);
        
        // 设置用户头像
        // 在实际应用中，应该使用图片加载库（如Glide或Picasso）加载头像
        holder.ivAvatar.setImageResource(R.drawable.default_avatar);
        
        // 设置用户名称
        holder.tvName.setText(contact.getName());
        
        // 设置用户ID
        String idType = determineIdType(contact.getId());
        holder.tvId.setText(idType + ": " + contact.getId());
        
        // 设置地区
        String region = contact.getRegion();
        if (region != null && !region.isEmpty()) {
            holder.tvRegion.setText("地区: " + region);
            holder.tvRegion.setVisibility(View.VISIBLE);
        } else {
            holder.tvRegion.setVisibility(View.GONE);
        }
        
        // 设置添加按钮状态
        updateAddButtonState(holder, contact.getId());
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onResultClick(contact);
            }
        });
        
        // 设置添加按钮点击事件 - 跳转到好友申请页面
        holder.btnAdd.setOnClickListener(v -> {
            if (listener != null) {
                // 直接回调点击事件，跳转到好友申请页面
                listener.onAddClick(contact);
            }
        });
    }
    
    /**
     * 更新添加按钮状态
     */
    private void updateAddButtonState(ViewHolder holder, String contactId) {
        int status = addFriendStatus.getOrDefault(contactId, STATUS_NOT_ADDED);
        
        switch (status) {
            case STATUS_NOT_ADDED:
                holder.btnAdd.setText("添加");
                holder.btnAdd.setEnabled(true);
                holder.btnAdd.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_button_green));
                holder.btnAdd.setTextColor(ContextCompat.getColor(context, android.R.color.white));
                break;
                
            case STATUS_REQUESTING:
                holder.btnAdd.setText("请求中...");
                holder.btnAdd.setEnabled(false);
                holder.btnAdd.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_button_gray));
                holder.btnAdd.setTextColor(ContextCompat.getColor(context, android.R.color.white));
                break;
                
            case STATUS_REQUEST_SENT:
                holder.btnAdd.setText("已发送");
                holder.btnAdd.setEnabled(false);
                holder.btnAdd.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_button_gray));
                holder.btnAdd.setTextColor(ContextCompat.getColor(context, android.R.color.white));
                break;
                
            case STATUS_ADDED:
                holder.btnAdd.setText("已添加");
                holder.btnAdd.setEnabled(false);
                holder.btnAdd.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_button_gray));
                holder.btnAdd.setTextColor(ContextCompat.getColor(context, android.R.color.white));
                break;
        }
    }
    
    /**
     * 从外部更新添加按钮状态
     * @param contactId 联系人ID
     * @param status 按钮状态
     */
    public void updateAddButtonStatus(String contactId, int status) {
        if (contactId != null) {
            addFriendStatus.put(contactId, status);
            notifyDataSetChanged();
        }
    }
    
    /**
     * 确定ID类型（微信号/手机号/邮箱）
     */
    private String determineIdType(String id) {
        if (id.contains("@")) {
            return "邮箱";
        } else if (id.matches("\\d{11}")) {
            return "手机号";
        } else {
            return "账号";
        }
    }
    
    /**
     * 重置所有添加状态
     */
    public void resetAddStatus() {
        addFriendStatus.clear();
        notifyDataSetChanged();
    }
    
    @Override
    public int getItemCount() {
        return results.size();
    }
    
    /**
     * ViewHolder类
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tvName;
        TextView tvId;
        TextView tvRegion;
        Button btnAdd;
        
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvName = itemView.findViewById(R.id.tv_name);
            tvId = itemView.findViewById(R.id.tv_id);
            tvRegion = itemView.findViewById(R.id.tv_region);
            btnAdd = itemView.findViewById(R.id.btn_add);
        }
    }
    
    /**
     * 搜索结果点击监听接口
     */
    public interface OnResultClickListener {
        void onResultClick(Contact contact);
        void onAddClick(Contact contact);
    }
}